# -*- coding: utf-8 -*-
'''
    :file: utils.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/02/13 21:13:14
'''
from flask.globals import current_app, g
# from flask_sqlalchemy import SQLAlchemy
from itsdangerous import BadSignature, SignatureExpired, TimedJSONWebSignatureSerializer as Serializer
# from sqlalchemy.sql.functions import user
from datetime import datetime

# 格式化分享时间
def make_share_time(second):
    """
    @description: 返回分享码时间
    ---------
    @param: second
    -------
    @Returns: 分享码时间(半天为单位)
    -------
    """
    return second*3600*12

# 获取当前时间戳
def get_now_timestamp():
    """   返回JavaScript的时间戳   """
    return datetime.now().timestamp() * 1000

# 格式化响应体
def make_res(code: int = 200, message: str = "ok", data: any = [], time = get_now_timestamp()) -> dict:
    """
    @description: make respones body.
    ---------
    @param: code:int, status code.
    @param: message:str, message value.
    @param: data:any, The api value body for return.
    @param: time:datetime, The time when api return.
    -------
    @Returns: dict.
    -------
    """
    return {
        "status": code,
        "message": message,
        "data": data,
        "time": time
    }

# 检测路径是否安全
def is_safe_path(path: str):
    path = path.replace("\\", "/")
    path = path.split("/")
    return False if ".." in path else True

# 下载鉴权(下载token解析)
def download_validate_token(token):
    g.user = None
    g.username = None
    try:
        data = Serializer(current_app.config['SECRET_KEY']).loads(token)
    except Exception as e:
        return False
    if "id" in data:
        g.user = data["id"]
        g.username = data['username']
        return True
    return False

# 重置密码token解析
def validate_token(token):
    s = Serializer(current_app.config['RESET_SECRET_KEY'])
    try:
        data = s.loads(token)
    except SignatureExpired:
        # valid token, but expired
        raise TokenTimeout("Token过期")
    except BadSignature:
        raise BadSignature
    return data

# 生成令牌(token)
def generate_token(code: str, user, expiration=300):
    s = Serializer(current_app.config["RESET_SECRET_KEY"], expires_in=expiration)
    return s.dumps({
        "id": user.id,
        'code': code
    }).decode()


class TokenTimeout(Exception):
    def __init__(self, msg) -> None:
        self.msg = msg

    def __str__(self) -> str:
        return self.msg

